// pages/order/placeOrder.js
const utils = require('../../utils/util.js');
const api = require('../../config/api.js');
const https = require('../../utils/request.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    stateOptions: [],
    sizeOptions: [],

    pageType: '',
    orderId: '',
    orderInfo: '',


    // 3D人像
    threeObject: {
      name: '3D人像',
      size: '3cm',
      price: 99,
      id: ''
    },

    // 真人手办
    zrObject: {
      name: '真人手办',
      size: '',
      price: 0
    },

    orderAddress: {
      src: '',
      name: '',
      iphone: '',
    },
    number: 1,
    totalPrice: 0, // 实付金额
    price: 0, // 实付金额（后台）
    saveLoading: false,


  },

  // 收货地址
  onAddress() {
    let that = this;
    if (that.data.orderId) {
      return false;
    }
    wx.chooseAddress({
      success(res) {
        let {
          userName,
          telNumber,
          provinceName,
          cityName,
          countyName,
          detailInfo
        } = res;
        console.log('收货地址：', res);
        that.setData({
          orderAddress: {
            src: provinceName + ' ' + cityName + ' ' + countyName + ' ' + detailInfo,
            name: userName,
            iphone: telNumber
          }
        })
      }
    })
  },
  // 修改数量
  onStepperChange(e) {
    let that = this;
    let thatNumber = e.detail;
    // console.log(e.detail)
    let thatPrice = that.data.threeObject.price;
    let thatTotalPrice = utils.mul(thatNumber, thatPrice, 2);
    console.log('总价：', thatTotalPrice)
    that.setData({
      totalPrice: utils.mul(thatTotalPrice, 100),
      price: thatTotalPrice,
      number: thatNumber
    })

  },

  // 提交
  onSubmit() {
    let that = this;
    if (that.data.orderId) {
      let {
        time,
        prepay_id,
        sign,
        paySign,
        nonce_str
      } = that.data.orderInfo.paymenttoVo;
      let playData = {
        timeStamp: time,
        nonceStr: nonce_str,
        package: prepay_id,
        signType: sign,
        paySign: paySign
      }
      that.playOrder(playData)
      return false
    }
    // 判断地址是否选择
    if (!that.data.orderAddress.name) {
      wx.showToast({
        icon: 'none',
        title: '请先选择收货地址',
      })
      return false;
    } else {}
    let params = {
      id: that.data.threeObject.id,
      openid: wx.getStorageSync('openid'),
      ...that.data.orderAddress,
      numbers: that.data.number,
      price: that.data.price
    }
    console.log('下单', params);
    that.setData({
      saveLoading: true
    })
    https.request(api.OrderPlayBySingle, params, 'post').then(res => {
      console.log('下单：', res)
      that.setData({
        saveLoading: false
      })
      if (res.error_code == 0) {
        // 发起支付
        let playData = {
          timeStamp: res.data.time,
          nonceStr: res.data.nonce_str,
          package: res.data.prepay_id,
          signType: res.data.sign,
          paySign: res.data.paySign
        }
        that.playOrder(playData)
      } else {
        wx.showToast({
          icon: 'none',
          title: res.message,
        })
      }
    }).catch(err => {
      that.setData({
        saveLoading: false
      })
      console.log('下单错误', err)
    })


  },

  // 发起支付
  playOrder(playData) {
    let that = this;
    // let playData = that.orderInfo.playJson;
    // 发起支付
    wx.showLoading()
    wx.requestPayment({
      timeStamp: playData.timeStamp,
      nonceStr: playData.nonceStr,
      package: 'prepay_id=' + playData.package,
      signType: 'MD5',
      paySign: playData.paySign,
      fail: function (err) {
        wx.hideLoading()
        console.error(err)
        wx.showToast({
          icon: 'none',
          title: '支付失败:' + err
        });
        wx.switchTab({
          url: '/pages/order/order',
        })
      },
      success: function () {
        wx.hideLoading()
        // 提示支付成功
        wx.showToast({
          icon: 'none',
          title: '支付成功'
        })
        wx.switchTab({
          url: '/pages/order/order'
        });
      }
    })

  },

  copyOrderCode(e) {
    let message = e.currentTarget.dataset.message;
    wx.setClipboardData({
      data: message,
      success(res) {
        wx.showToast({
          title: '订单编号：' + message + '，复制成功',
          icon: 'none',
          duration: 5000
        })
      }
    })
  },

  // 初始化字典
  async initDict() {
    let that = this;
    // 字典
    let status = await https.request(api.OrderStatus, {}, 'post');
    let size = await https.request(api.MatrixSize, {}, 'post');
    console.log('字典1', status)
    console.log('字典2', size)
    if (!(status.data && status.data.length && size.data && size.data.length > 0)) {
      wx.showToast({
        title: '服务器错误',
        icon: 'none'
      })
      return false;
    }
    that.setData({
      stateOptions: status.data.map(res => {
        return {
          code: res.state_id,
          label: res.state_name
        }
      }),
      sizeOptions: size.data.map(res => {
        return {
          code: res.id,
          label: res.size_name
        }
      })
    })
    return true;
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    // single下单、待付款、待收货/已完成
    let that = this;
    wx.showLoading()
    let initDict = await that.initDict();
    if (!initDict) {
      return false;
    }

    let pageType = options.pageType; // 页面类型（single、matrix）
    let orderId = options.orderId; // 订单id
    that.setData({
      pageType: pageType,
      orderId: orderId
    })
    if (orderId) {
      // 获取订单详情
      https.request(api.OrderInfo, {
        order_id: orderId
      }, 'post').then(res => {
        wx.hideLoading()
        if (res.error_code == 0) {
          console.log('更新订单列表', res.data)
          let {
            src,
            name,
            iphone,
            actualprice
          } = res.data;
          that.setData({
            orderInfo: res.data,
            orderAddress: {
              src: src,
              name: name,
              iphone: iphone,
            },
            totalPrice: utils.mul(actualprice, 100),
            price: actualprice,
            number:res.data.numbers
          })
        }
      }).catch(err => {
        wx.hideLoading()
        console.log('错误', err)
      })
    } else {
      // single下单
      let modelId = options.id; // 模型id
      console.log('下单参数：', pageType + '_' + modelId);
      // modelId = '149';
      that.setData({
        'threeObject.id': modelId
      })
      that.onStepperChange({
        detail: 1
      }); // 默认计算数量1

      wx.hideLoading()
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})